package com.itfallrain.common;

import com.itfallrain.entity.User;
import com.itfallrain.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//权限验证
public class MainInterceptor implements HandlerInterceptor {
    @Autowired
    private AuthService authService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("login_id") == null) {
            return false;
        } else {
            HandlerMethod hand = (HandlerMethod) o;
//            通过反射获取UserAuth类，在返回给UserAuth对象（通过类获取类对象）
            UserAuth userAuth = hand.getMethodAnnotation(UserAuth.class);
//            如果不加参数拦截就返回真
            if (userAuth == null) {
                return true;
            }
//            获取拦截的值
            int auth = userAuth.value();
//            获取前端页面的用户
            User u = (User) session.getAttribute("login_id");
//            获取用户权限id
            int role = u.getRoleId();

            return authService.getByRoleId(role, auth);
        }
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
